<script setup lang="ts">
import { reactive, computed, onMounted } from 'vue';
import {
  eventCenter,
  getCurrentInstance,
  navigateTo,
  showLoading,
  hideLoading,
} from '@tarojs/taro';
import dayjs from 'dayjs';
import {
  WORK_ORDER_STATUS,
  WORK_ORDER_STATUS_COLOR,
  WORK_ORDER_STATUS_BG_COLOR,
} from '/@/common/constant';
import { LOGIN_APP } from '/@/api/modules/base/app-sys-user';
import {
  QUERY_APP_WORK_ORDER_DETAIL,
  EVALUATE_APP_TASK,
} from '/@/api/modules/order/app-work-order';
import { getSysImgUrl } from '/@/utils/index';
import IMG_ICON_COOPERATE from '/@/assets/image/icon/cooperate.png';
import IMG_ICON_SPEED from '/@/assets/image/icon/speed.png';

/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as {
  id: string;
  from?: string;
  assetId?: string;
};

const state = reactive<{
  /**
   * 工单信息
   */
  info: AppSysWorkOrder.Dto;
  uaaUserId: string;
  /**
   * taro应用环境
   */
  taroEnv: string;
}>({
  info: {},
  uaaUserId: '',
  taroEnv: process.env.TARO_ENV,
});

/**
 * 工单评价表单
 */
const evaluateTaskFormState = reactive<{
  workOrderEventDto: AppSysWorkOrder.eventDto;
  workOrderDto: AppSysWorkOrder.Dto;
}>({
  workOrderEventDto: {
    workOrderId: '',
    handleUserId: '',
    handleUserName: '',
    handleTime: undefined,
    opinion: '',
    starNumber: 0,
    starNumberQuality: 0,
  },
  workOrderDto: {
    id: '',
  },
});

/**
 * 图片文件列表
 */
const imgList = computed(() => {
  if (!state.info.workOrderFileDto || !state.info.workOrderFileDto.length) return [];

  return [...(state.info.workOrderFileDto as AppSysWorkOrder.FileDto[])]
    .filter((file) => {
      return file.fileType === 1;
    })
    .map((file) => {
      return {
        key: file.id || '',
        src: file.fileUrl || '',
      };
    });
});

/**
 * 钉钉音频在服务端的标识
 */
const audioSrc = computed(() => {
  if (!state.info.workOrderFileDto || !state.info.workOrderFileDto.length) return '';

  const audioList = [...(state.info.workOrderFileDto as AppSysWorkOrder.FileDto[])].filter(
    (file) => {
      return file.fileType === 2 && file.fileName?.includes('.mp3');
    },
  );

  return audioList && audioList.length ? audioList[0].fileUrl : '';
});

/**
 * 微信音频
 */
const wxAudioSrc = computed(() => {
  if (!state.info.workOrderFileDto || !state.info.workOrderFileDto.length) return '';

  const audioList = [...(state.info.workOrderFileDto as AppSysWorkOrder.FileDto[])].filter(
    (file) => {
      return file.fileType === 2 && file.fileName?.includes('wx-audio');
    },
  );

  return audioList && audioList.length ? audioList[0].fileUrl : '';
});

/**
 * @function 获取工单详情
 */
function getDetail() {
  showLoading();
  QUERY_APP_WORK_ORDER_DETAIL({ id: params.id }).then((res) => {
    state.info = res.workOrderDto;

    const evaluateTaskEventIndex = state.info.workOrderEventDto?.findIndex((item) => {
      return item.eventCode === 'evaluate_task';
    });

    if (evaluateTaskEventIndex && evaluateTaskEventIndex > 0) {
      evaluateTaskFormState.workOrderEventDto.starNumber = (
        state.info.workOrderEventDto as AppSysWorkOrder.eventDto[]
      )[evaluateTaskEventIndex].starNumber;
      evaluateTaskFormState.workOrderEventDto.starNumberQuality = (
        state.info.workOrderEventDto as AppSysWorkOrder.eventDto[]
      )[evaluateTaskEventIndex].starNumberQuality;
      evaluateTaskFormState.workOrderEventDto.opinion = (
        state.info.workOrderEventDto as AppSysWorkOrder.eventDto[]
      )[evaluateTaskEventIndex].opinion;
    }

    hideLoading();
  });
}

/**
 * @function 评价订单
 */
function evaluateTask() {
  LOGIN_APP().then((res) => {
    evaluateTaskFormState.workOrderDto.id = params.id;
    evaluateTaskFormState.workOrderEventDto.workOrderId = params.id;
    evaluateTaskFormState.workOrderEventDto.handleUserId = res.sysUserDto.id;
    evaluateTaskFormState.workOrderEventDto.handleUserName = res.sysUserDto.name;
    evaluateTaskFormState.workOrderEventDto.handleTime = new Date().valueOf();

    EVALUATE_APP_TASK(evaluateTaskFormState).then(() => {
      getDetail();
    });
  });
}

onMounted(() => {
  eventCenter.on(getCurrentInstance().router?.onShow as string, () => {
    getDetail();
    LOGIN_APP().then((res) => {
      state.uaaUserId = res.sysUserDto.uaaUserId || '';
    });
  });
});
</script>

<template>
  <view class="work-order-detail app-page--1">
    <app-navbar title="工单详情" />
    <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
      <view class="work-order-detail__wrapper">
        <nut-cell-group>
          <nut-cell>
            <template v-slot:title>
              <view class="work-order-detail__module-title-wrapper">
                <text class="work-order-detail__module-title">工单详情</text>
                <image
                  v-if="state.info.hastenStatus === 2"
                  class="work-order-detail__icon"
                  :src="IMG_ICON_SPEED"
                />
                <image
                  v-if="state.info.cooperateStatus === 1"
                  class="work-order-detail__icon"
                  :src="IMG_ICON_COOPERATE"
                />
              </view>
            </template>
            <template v-slot:link>
              <view>
                <text
                  class="work-order-detail__status"
                  :style="{
                    color: state.info.status ? WORK_ORDER_STATUS_COLOR[state.info.status] : '#999',
                    backgroundColor: state.info.status
                      ? WORK_ORDER_STATUS_BG_COLOR[state.info.status]
                      : '#999',
                  }"
                >
                  {{ state.info.status ? WORK_ORDER_STATUS[state.info.status] : '-' }}
                </text>
              </view>
            </template>
          </nut-cell>
          <nut-cell title="工单号" :desc="state.info.orderCode || '-'" />
          <nut-cell title="类型" :desc="state.info.orderTypeName || '-'" />
          <nut-cell title="子类" :desc="state.info.orderSubTypeName || '-'" />
          <nut-cell title="来源" :desc="state.info.orderSourceName || '-'" />
          <nut-cell title="地点" :desc="state.info.areaName || '-'" />
          <nut-cell title="故障设备" :desc="state.info.assetName || '-'" />
          <nut-cell
            title="提单人"
            :desc="`${state.info.releaseUserName}(${state.info.releaseUserPhone})` || '-'"
          />
          <nut-cell
            title="创建时间"
            :desc="dayjs(state.info.createTime).format('YYYY-MM-DD HH:mm:ss') || '-'"
          />
          <nut-cell title="工单描述" :desc="state.info.description || '-'" />
          <nut-cell center title="语音" v-if="audioSrc || wxAudioSrc">
            <template v-slot:link>
              <app-wx-record-audio
                v-if="state.taroEnv === 'weapp' && wxAudioSrc"
                :url="getSysImgUrl(wxAudioSrc)"
                readonly
              />
              <app-dd-record-audio
                v-else-if="state.taroEnv === 'h5' && audioSrc"
                :url="audioSrc"
                readonly
              />
            </template>
          </nut-cell>
          <nut-cell v-if="imgList && imgList.length">
            <app-upload-image :default-image-list="imgList" :readonly="true" height="120px" />
          </nut-cell>
        </nut-cell-group>
        <nut-cell-group>
          <nut-cell>
            <template v-slot:title>
              <text class="work-order-detail__module-title">工单轨迹</text>
            </template>
          </nut-cell>
          <nut-cell>
            <app-work-order-event-list :list="state.info.workOrderEventDto" />
          </nut-cell>
        </nut-cell-group>
        <nut-cell-group v-if="state.info.stockRecordDto && state.info.stockRecordDto.length">
          <nut-cell>
            <template v-slot:title>
              <text class="work-order-detail__module-title">耗材领用</text>
            </template>
          </nut-cell>
          <nut-cell>
            <view class="work-order-detail-stock-table">
              <view class="work-order-detail-stock-table__header">
                <view class="work-order-detail-stock-table__header-item" :style="{ width: '40%' }">
                  申请单号
                </view>
                <view
                  class="work-order-detail-stock-table__header-item"
                  :style="{ width: `calc(60% * 0.7)` }"
                >
                  耗材名称
                </view>
                <view
                  class="work-order-detail-stock-table__header-item"
                  :style="{ width: 'calc(60% * 0.3)' }"
                >
                  数量
                </view>
              </view>
              <view class="work-order-detail-stock-table__body">
                <view
                  v-for="item in state.info.stockRecordDto"
                  :key="item.id"
                  class="work-order-detail-stock-item"
                >
                  <view class="work-order-detail-stock-item__code">{{
                    item.recordCode || '-'
                  }}</view>
                  <view class="work-order-detail-stock-item__spare-wrapper">
                    <view
                      v-for="stockItem in item.content"
                      :key="stockItem.id"
                      class="work-order-detail-stock-item__spare"
                    >
                      <view class="work-order-detail-stock-item__spare-name">
                        {{ stockItem.spare ? stockItem.spare.spareName : '-' }}
                      </view>
                      <view class="work-order-detail-stock-item__spare-num">{{
                        stockItem.operateNum || 0
                      }}</view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </nut-cell>
        </nut-cell-group>

        <nut-cell-group
          v-if="state.info.status === 'task_complete' && state.info.evaluateTask === 1"
        >
          <nut-cell>
            <template v-slot:title>
              <text class="work-order-detail__module-title">工单评价</text>
            </template>
          </nut-cell>
          <nut-cell title="服务时间">
            <template v-slot:link>
              <nut-rate
                v-model="evaluateTaskFormState.workOrderEventDto.starNumber"
                readonly
                active-color="#ffc800"
              />
            </template>
          </nut-cell>
          <nut-cell title="服务质量">
            <template v-slot:link>
              <nut-rate
                v-model="evaluateTaskFormState.workOrderEventDto.starNumberQuality"
                readonly
                active-color="#ffc800"
              />
            </template>
          </nut-cell>
          <nut-cell title="评价内容">
            <template v-slot:link>
              <text>
                {{ evaluateTaskFormState.workOrderEventDto.opinion || '-' }}
              </text>
            </template>
          </nut-cell>
        </nut-cell-group>

        <nut-cell-group
          v-else-if="
            state.info.status === 'task_complete' &&
            state.info.evaluateTask === 2 &&
            params.from === 'report-history'
          "
        >
          <nut-cell>
            <template v-slot:title>
              <text class="work-order-detail__module-title">工单评价</text>
            </template>
          </nut-cell>
          <nut-cell title="服务时间">
            <template v-slot:link>
              <nut-rate
                v-model="evaluateTaskFormState.workOrderEventDto.starNumber"
                active-color="#ffc800"
              />
            </template>
          </nut-cell>
          <nut-cell title="服务质量">
            <template v-slot:link>
              <nut-rate
                v-model="evaluateTaskFormState.workOrderEventDto.starNumberQuality"
                active-color="#ffc800"
              />
            </template>
          </nut-cell>
          <nut-cell title="评价内容">
            <template v-slot:link>
              <nut-textarea
                class="work-order-detail__evaluate-task-textarea"
                v-model="evaluateTaskFormState.workOrderEventDto.opinion"
                limit-show
                rows="5"
                max-length="50"
              />
            </template>
          </nut-cell>
        </nut-cell-group>
      </view>
    </scroll-view>

    <view
      v-if="
        state.info.status === 'task_complete' &&
        state.info.evaluateTask === 2 &&
        params.from === 'report-history'
      "
      class="work-order-detail__footer"
    >
      <nut-button
        class="work-order-detail__footer-btn"
        shape="round"
        type="info"
        @click="evaluateTask"
      >
        提交评价
      </nut-button>
    </view>

    <view
      v-if="
        state.info.status === 'task_receive' &&
        state.info.resolverUserId === state.uaaUserId &&
        (params.from === 'report-history' ? state.info.releaseUserId !== state.uaaUserId : true)
      "
      class="work-order-detail__footer"
    >
      <nut-button
        class="work-order-detail__footer-btn"
        shape="round"
        type="info"
        @click="navigateTo({ url: `/pages/work-order/receive/index?id=${params.id}` })"
      >
        接单
      </nut-button>
      <nut-button
        class="work-order-detail__footer-btn"
        shape="round"
        type="danger"
        @click="
          () => {
            navigateTo({
              url: `/pages/work-order/back/index?id=${params.id}&from=${params.from}&assetId=${params.assetId}`,
            });
          }
        "
      >
        回退
      </nut-button>
    </view>

    <view v-else-if="state.info.status === 'task_suspend'" class="work-order-detail__footer">
      <nut-button
        class="work-order-detail__footer-btn"
        shape="round"
        type="info"
        @click="navigateTo({ url: `/pages/work-order/resume/index?id=${params.id}` })"
      >
        解挂
      </nut-button>
    </view>

    <view
      v-else-if="
        state.info.orderUserDtos?.filter((user) => {
          return user.userId === state.uaaUserId && user.status === 'task_process';
        }).length
      "
      class="work-order-detail__footer"
    >
      <nut-button
        class="work-order-detail__footer-btn"
        shape="round"
        type="warning"
        @click="
          () => {
            navigateTo({
              url: `/pages/work-order/cooperate-complete/index?id=${params.id}&from=${params.from}&assetId=${params.assetId}`,
            });
          }
        "
      >
        处理
      </nut-button>
    </view>

    <view
      v-else-if="
        state.info.status === 'task_process' &&
        !state.info.orderUserDtos?.filter((user) => {
          return user.userId === state.uaaUserId;
        }).length
      "
      class="work-order-detail__footer"
    >
      <nut-button
        class="work-order-detail__footer-btn"
        shape="round"
        :type="
          (state.info.orderUserDtos?.filter((user) => {
            return user.status === 'task_process';
          }).length || 0) > 0
            ? 'default'
            : 'warning'
        "
        :disabled="
          (state.info.orderUserDtos?.filter((user) => {
            return user.status === 'task_process';
          }).length || 0) > 0
        "
        @click="
          () => {
            navigateTo({
              url: `/pages/work-order/process/index?id=${params.id}&from=${params.from}&assetId=${params.assetId}`,
            });
          }
        "
      >
        处理
      </nut-button>
      <nut-button
        class="work-order-detail__footer-btn"
        shape="round"
        type="info"
        @click="
          () => {
            navigateTo({
              url: `/pages/work-order/forward/index?id=${params.id}&from=${params.from}&assetId=${params.assetId}`,
            });
          }
        "
      >
        转派
      </nut-button>
      <nut-button
        class="work-order-detail__footer-btn"
        shape="round"
        type="info"
        @click="
          () => {
            navigateTo({
              url: `/pages/work-order/handle-more/index?id=${params.id}&from=${params.from}&assetId=${params.assetId}`,
            });
          }
        "
      >
        更多
      </nut-button>
      <!-- <nut-button
        class="work-order-detail__footer-btn"
        shape="round"
        size="small"
        type="info"
        @click="
          () => {
            navigateTo({
              url: `/pages/work-order/suspend/index?id=${params.id}&from=${params.from}&assetId=${params.assetId}`,
            });
          }
        "
      >
        挂起
      </nut-button> -->
    </view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
